package com.aidex.biz.service.impl;

import com.aidex.biz.domain.*;
import com.aidex.biz.domain.enums.DongTaiTypeEnum;
import com.aidex.biz.mapper.CustomerShadowInfoMapper;
import com.aidex.biz.messageSend.MessageSendService;
import com.aidex.biz.service.*;
import com.aidex.common.annotation.DataScope;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.core.service.BaseServiceImpl;
import com.aidex.common.utils.NumberUtils;
import com.aidex.common.utils.SecurityUtils;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sms.ChuangLanSmsClient;
import com.aidex.framework.cache.ConfigUtils;
import com.aidex.system.service.CompanyService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;

/**
 * 客户跟踪Service业务层处理
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-08-06
 */
@Service
@Transactional(readOnly = true)
public class CustomerShadowInfoServiceImpl extends BaseServiceImpl<CustomerShadowInfoMapper, CustomerShadowInfo> implements CustomerShadowInfoService {
    private static final Logger log = LoggerFactory.getLogger(CustomerShadowInfoServiceImpl.class);
    @Autowired
    private CustomerService customerInfoService;
    @Autowired
    private ToHomeService toHomeService;

    @Autowired
    private CustomerXiezuService customerXiezuService;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;

    @Autowired
    private MessageSendService messageSendService;


    @Autowired
    private CompanyService companyService;

    @Autowired
    private XiansuoChengbenLogService xiansuoChengbenLogService;

    /**
     * 获取单条数据
     *
     * @param customerShadowInfo 客户跟踪
     * @return 客户跟踪
     */
    @Override
    public CustomerShadowInfo get(CustomerShadowInfo customerShadowInfo) {
        CustomerShadowInfo dto = super.get(customerShadowInfo);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 客户跟踪id
     * @return 客户跟踪
     */
    @Override
    public CustomerShadowInfo get(String id) {
        CustomerShadowInfo dto = super.get(id);
        return dto;
    }


    /**
     * 查询客户跟踪列表
     *
     * @param customerShadowInfo 客户跟踪
     * @return 客户跟踪
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public List<CustomerShadowInfo> findList(CustomerShadowInfo customerShadowInfo) {
        return super.findList(customerShadowInfo);
    }

    /**
     * 分页查询客户跟踪列表
     *
     * @param customerShadowInfo 客户跟踪
     * @return 客户跟踪
     */
    @Override
    @DataScope(userAlias = "a", deptAlias = "a")
    public PageInfo<CustomerShadowInfo> findPage(CustomerShadowInfo customerShadowInfo) {
        return super.findPage(customerShadowInfo);
    }

    /**
     * 删除客户跟踪信息
     *
     * @param customerShadowInfo
     * @return 结果
     */
    @Override
    public boolean remove(CustomerShadowInfo customerShadowInfo) {
        return super.remove(customerShadowInfo);
    }

    /**
     * 批量删除客户跟踪
     *
     * @param ids 需要删除的客户跟踪ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteCustomerShadowInfoByIds(String[] ids) {
        return mapper.deleteCustomerShadowInfoByIds(ids);
    }

    /**
     * 获取最大编号
     *
     * @param customerShadowInfo 客户跟踪
     * @return 结果
     */
    @Override
    public int findMaxSort(CustomerShadowInfo customerShadowInfo) {
        return NumberUtils.nextOrder(mapper.findMaxSort(customerShadowInfo));
    }

    @Override
    public PageInfo<CustomerShadowInfo> findMylist(CustomerShadowInfo customerShadowInfo) {
        return super.findPage(customerShadowInfo);
    }

    @Override
    public List<CustomerShadowInfo> findShadowListByCustomerIds(List<String> ids) {
        if (null != ids && !ids.isEmpty()) {
            return mapper.findShadowListByCustomerIds(ids);
        }
        return null;
    }

    @Override
    public boolean addCustomerShadowInfo(CustomerShadowInfo customerShadowInfo, Customer customerInfo) throws ParseException {
        if (null != customerInfo) {
            // 如果有预约上门则创建预约上门信息
            if ("1".equals(customerShadowInfo.getIsToHome())) {
                ToHome toHome = new ToHome();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                toHome.setYuyueTime(simpleDateFormat.parse(customerShadowInfo.getToHomeTime()));
                toHome.setCustomerId(customerShadowInfo.getCustomerId());
                toHome.setStatus("0"); // 正常
                toHome.setTuofei(0); // 不作废
                toHome.setQyStatus(0);
                toHome.setIsSms(customerShadowInfo.getIsSms());
                toHome.setLaiyuan(customerInfo.getLaiyuan());
                toHome.setCompanyNames(customerShadowInfo.getCompanyNames());
                toHome.setToHomeCompanyId(customerShadowInfo.getToHomeCompanyId());// 上门公司id

                String content = SecurityUtils.getLoginUser().getUser().getName() + "-邀约上门-" + customerInfo.getCusName() +
                        "-上门时间【" + customerShadowInfo.getToHomeTime() + "】";
                if (StringUtils.isNotNull(toHome.getIsSms()) && toHome.getIsSms() == 1) {
                    content += "-邀请码【" + toHome.getInviteCode() + "】";
                    // 发送短信
                    String params =
                            customerInfo.getPhone() + "," + customerInfo.getCusName() + "," + customerShadowInfo.getToHomeTime().substring(0, 16) +
                                    "," +
                                    "【" + toHome.getInviteCode() + "】";
                    ChuangLanSmsClient.sendVariableSms(params);
                }

                // 获取线索成本记录表对应的记录
                XiansuoChengbenLog xiansuoChengbenLog = new XiansuoChengbenLog();
                xiansuoChengbenLog.setLaiyuan(toHome.getLaiyuan());
                xiansuoChengbenLog.setCustomerId(toHome.getCustomerId());
                List<XiansuoChengbenLog> xiansuoChengbenLogList = xiansuoChengbenLogService.findList(xiansuoChengbenLog);
                if (null != xiansuoChengbenLogList && !xiansuoChengbenLogList.isEmpty()) {
                    xiansuoChengbenLog = xiansuoChengbenLogList.get(0);
                    toHome.setXscbLogId(xiansuoChengbenLog.getId());
                }

                // 添加业务动态
                CustomerDongtai customerDongtai = new CustomerDongtai();
                customerDongtai.setCustomerId(customerInfo.getId());
                customerDongtai.setType(DongTaiTypeEnum.JINJIAN.getStatus());
                customerDongtai.setContent(content);
                customerDongtaiService.save(customerDongtai);


                // 发送邀约上门提醒微信
//                【新增邀约上门提醒】\n
//                客户姓名：%s\n
//                车牌号：%s\n
//                评估价:  %s万\n
//                公里数：%s\n
//                上牌日期: %s\n
//                车辆状态：%s\n
//                需求资金: %s\n
//                征信:  %s\n
//                备注：%s\n
//                推荐方案：%s\n
//                融资顾问:%s\n

                if (customerShadowInfo.getIsVxs() == 1) {
                    String companyName = Objects.toString(customerShadowInfo.getCompanyNames(), "");

                    if (StringUtils.isNotEmpty(companyName)) {
                        companyName = companyName.replace("[", "").replace("]", "").replace("\"", "");
                    }

                    String cusName = Objects.toString(customerInfo.getCusName(), "");
                    String carNo = Objects.toString(customerInfo.getCarNo(), "");
                    String pgPrice = Objects.toString(customerInfo.getPgPrice(), "");
                    String mileage = Objects.toString(customerInfo.getMileage(), "～");
                    String fuckCarNoTime = Objects.toString(customerInfo.getFuckCarNoTime(), "");
                    String carStatus = Objects.toString(customerInfo.getCarStatus(), "");
                    String amount = Objects.toString(customerInfo.getAmount(), "");
                    String zx = Objects.toString(customerInfo.getZx(), "");
                    String shadow = Objects.toString(customerShadowInfo.getTakes(), "");
                    String toHomeTime = Objects.toString(customerShadowInfo.getToHomeTime(), "");
                    String userName = Objects.toString(SecurityUtils.getLoginUser().getUser().getName(), "");


                    String wxMsgModel = ConfigUtils.getConfigValueByKey("wxWork.model.toHome.new");
                    if (StringUtils.isNotNull(wxMsgModel)) {
                        content = String.format(wxMsgModel.replace("\\n", "\n"),
                                companyName,
                                cusName,
                                carNo,
                                pgPrice,
                                mileage,
                                fuckCarNoTime,
                                carStatus,
                                amount,
                                zx,
                                shadow,
                                toHomeTime,
                                userName
                        );
                        SysUser sysUser = new SysUser();
                        sysUser.setPhonenumber("@all");//艾特所有人
                        String toHomeCompanyId = toHome.getToHomeCompanyId();
                        String yaoyueCompanyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
                        
                        Company toHomeCompany = companyService.get(toHomeCompanyId);
                        if (null != toHomeCompany) {
                            String robotAddress = toHomeCompany.getRemark();
                            messageSendService.sendMessageWxWorkToGroup(robotAddress, content, new String[]{sysUser.getPhonenumber()});
                        }

                        // 异地邀约 两个公司都发消息
                        if (!toHomeCompanyId.equals(yaoyueCompanyId)) {
                            Company yaoyueCompany = companyService.get(yaoyueCompanyId);
                            if (null != yaoyueCompany) {
                                String robotAddress = yaoyueCompany.getRemark();
                                messageSendService.sendMessageWxWorkToGroup(robotAddress, content, new String[]{sysUser.getPhonenumber()});
                            }
                        }

                    }
                    toHome.setContent(content);
                }
                toHomeService.save(toHome);
            }
            CustomerXiezu customerXiezu = new CustomerXiezu();
            customerXiezu.setXiezuUserId(SecurityUtils.getUserId());
            customerXiezu.setCustomerId(customerInfo.getId());
            if (!customerXiezuService.findMyXieZuList(customerXiezu).getList().isEmpty()) {
                customerShadowInfo.setXiezu(1);
            } else {
                customerShadowInfo.setXiezu(0);
            }
            //发送短信联系客户
//            if (null != customerShadowInfo.getIsContactSms() && customerShadowInfo.getIsContactSms() == 1) {
//
//            }
            // 添加动态
            CustomerDongtai customerDongtai = new CustomerDongtai();
            customerDongtai.setCustomerId(customerShadowInfo.getCustomerId());
            customerDongtai.setType(DongTaiTypeEnum.SHADOW.getStatus());
            customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName() + "-新增跟进信息");
            customerDongtaiService.save(customerDongtai);
            return this.save(customerShadowInfo);
        } else {
            return false;
        }
    }
}
